package cn.com.css.taxInspection.zdgz.controller;

import cn.com.css.taxInspection.attention.entity.CljamxEntity;
import cn.com.css.taxInspection.attention.entity.QtjamxEntity;
import cn.com.css.taxInspection.attention.service.CljamxService;
import cn.com.css.taxInspection.attention.service.QtjamxService;
import cn.com.css.taxInspection.common.aop.annotation.LogAnnotation;
import cn.com.css.taxInspection.common.result.DataResult;
import cn.com.css.taxInspection.common.result.Result;
import cn.com.css.taxInspection.zdgz.entity.JaglYljamxEntity;
import cn.com.css.taxInspection.zdgz.service.JaglYljamxService;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 重点关注-积案管理
 */
@RequestMapping("/jagl")
@RestController
@Api(tags = "重点关注")
public class JaglController {

    @Resource
    private JaglYljamxService jaglYljamxService;
    @Resource
    private QtjamxService qtjamxService;
    @Resource
    private CljamxService cljamxService;

    private static final Logger log = LoggerFactory.getLogger(JaglController.class);

    @PostMapping("/jaglmx/importJaglData")
    @ApiOperation(value = "保存积案管理数据")
    @LogAnnotation(title = "积案管理", action = "保存积案管理数据")
    public DataResult importJaglData(@RequestParam(value = "file") MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<List<Object>> allAjbhList = reader.read(1, reader.getRowCount());
        // 清洗数据：提取第一列，转成去除中括号的字符串
        List<String> ajbhList = allAjbhList.stream()
                .map(row -> String.valueOf(row.get(0)).replaceAll("[\\[\\]]", "").trim())
                .collect(Collectors.toList());
        int importCount = jaglYljamxService.saveJaglData(ajbhList);
        return DataResult.success(importCount);
    }

    @PostMapping("/jaglmx/importYljamxData")
    @ApiOperation(value = "保存一类积案明细数据")
    @LogAnnotation(title = "积案管理", action = "保存一类积案明细数据")
    public ResponseEntity<?> importYljamxData(@RequestParam(value = "file") MultipartFile file) throws IOException {

        if (file == null || file.isEmpty() || file.getOriginalFilename() == null) {
            return ResponseEntity.ok(Result.error("上传的文件为空！"));
        }

        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet == null || sheet.getPhysicalNumberOfRows() <= 1) {
            workbook.close();
            return ResponseEntity.ok(Result.error("Excel 内容为空，至少需要包含一行数据！"));
        }
        int validDataCount = 0;
        for (Row row : sheet) {
            if (row.getRowNum() < 1 || isRowEmpty(row)) continue;
            // 组装数据
            JaglYljamxEntity jaglYljamxEntity = new JaglYljamxEntity();
            jaglYljamxEntity.setJcajbh(getStringCellValue(row.getCell(0)));
            jaglYljamxEntity.setJaqlqszhj(getStringCellValue(row.getCell(1)));
            jaglYljamxEntity.setCsjacy(getStringCellValue(row.getCell(2)));
            jaglYljamxEntity.setClyj(getStringCellValue(row.getCell(3)));
            jaglYljamxEntity.setYjqlrq(getDateCellValue(row.getCell(4)));
            validDataCount += jaglYljamxService.updateYljamxDataByJcajbh(jaglYljamxEntity);
        }
        workbook.close();
        if (validDataCount == 0) {
            return ResponseEntity.ok(Result.error("Excel 中没有有效的数据行！"));
        }
        return ResponseEntity.ok(Result.success(validDataCount));
    }

    @PostMapping("/jaglmx/importQtjamxData")
    @ApiOperation(value = "保存其他案明细数据")
    @LogAnnotation(title = "积案管理", action = "保存其他积案明细数据")
    public ResponseEntity<?> importQtjamxData(@RequestParam(value = "file") MultipartFile file) throws IOException {

        if (file == null || file.isEmpty() || file.getOriginalFilename() == null) {
            return ResponseEntity.ok(Result.error("上传的文件为空！"));
        }

        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet == null || sheet.getPhysicalNumberOfRows() <= 1) {
            workbook.close();
            return ResponseEntity.ok(Result.error("Excel 内容为空，至少需要包含一行数据！"));
        }

        int validDataCount = 0;

        for (Row row : sheet) {
            if (row.getRowNum() < 1 || isRowEmpty(row)) continue;
            // 组装数据
            QtjamxEntity qtjamxEntity = new QtjamxEntity();
            qtjamxEntity.setJcajbh(getStringCellValue(row.getCell(0)));
            qtjamxEntity.setWjyy(getStringCellValue(row.getCell(1)));
            qtjamxEntity.setClyj(getStringCellValue(row.getCell(2)));
            qtjamxEntity.setQlfs(getStringCellValue(row.getCell(3)));
            validDataCount += qtjamxService.updateQtjamxDataByJcajbh(qtjamxEntity);
        }
        workbook.close();
        if (validDataCount == 0) {
            return ResponseEntity.ok(Result.error("Excel 中没有有效的数据行！"));
        }
        return ResponseEntity.ok(Result.success(validDataCount));
    }

    @PostMapping("/jaglmx/importCljamxData")
    @ApiOperation(value = "保存其他案明细数据")
    @LogAnnotation(title = "积案管理", action = "保存其他积案明细数据")
    public ResponseEntity<?> importCljamxData(@RequestParam(value = "file") MultipartFile file) throws IOException {

        if (file == null || file.isEmpty() || file.getOriginalFilename() == null) {
            return ResponseEntity.ok(Result.error("上传的文件为空！"));
        }

        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet == null || sheet.getPhysicalNumberOfRows() <= 1) {
            workbook.close();
            return ResponseEntity.ok(Result.error("Excel 内容为空，至少需要包含一行数据！"));
        }

        int validDataCount = 0;

        for (Row row : sheet) {
            if (row.getRowNum() < 1 || isRowEmpty(row)) continue;
            // 组装数据
            CljamxEntity cljamxEntity = new CljamxEntity();
            cljamxEntity.setJcajbh(getStringCellValue(row.getCell(0)));
            cljamxEntity.setYqqk(getStringCellValue(row.getCell(1)));
            cljamxEntity.setWjyy(getStringCellValue(row.getCell(2)));
            cljamxEntity.setClyj(getStringCellValue(row.getCell(3)));
            validDataCount += cljamxService.updateCljamxDataByJcajbh(cljamxEntity);
        }
        workbook.close();
        if (validDataCount == 0) {
            return ResponseEntity.ok(Result.error("Excel 中没有有效的数据行！"));
        }
        return ResponseEntity.ok(Result.success(validDataCount));
    }

    @PostMapping("/jaglmx/queryJaglmxData")
    @ApiOperation(value = "查询一类积案明细")
    @LogAnnotation(title = "查询", action = "查询一类积案明细")
    public DataResult queryJaglmxData(@RequestBody JaglYljamxEntity jaglYljamxEntity) throws ParseException {
        IPage<JaglYljamxEntity> iPage = jaglYljamxService.queryJaglmxData(jaglYljamxEntity);
        return DataResult.success(iPage);
    }

    @PostMapping("/Yljamx/exportYljamxTable")
    @ApiOperation(value = "导出一类积案明细")
    @LogAnnotation(title = "一类积案明细", action = "导出一类积案明细")
    public DataResult exportYljamxTable(@RequestBody JaglYljamxEntity jaglYljamxEntity) throws ParseException {
        return DataResult.success(jaglYljamxService.exportYljamxTable(jaglYljamxEntity));
    }


    @PostMapping("/Qtjamx/exportQtjamxTable")
    @ApiOperation(value = "导出其他积案明细")
    @LogAnnotation(title = "积案管理", action = "导出其他积案明细")
    public DataResult exportQtjamxTable(@RequestBody QtjamxEntity qtjamxEntity) throws ParseException {
        return DataResult.success(qtjamxService.exportQtjamxTable(qtjamxEntity));
    }

    @PostMapping("/Cljamx/exportCljamxTable")
    @ApiOperation(value = "超六其他积案明细")
    @LogAnnotation(title = "积案管理", action = "超六其他积案明细")
    public DataResult exportCljamxTable(@RequestBody CljamxEntity cljamxEntity) throws ParseException {
        return DataResult.success(cljamxService.exportCljamxTable(cljamxEntity));
    }

    @PostMapping("/jaglmx/deleteBatch")
    @ApiOperation(value = "批量删除")
    @LogAnnotation(title = "积案管理", action = "批量删除积案管理数据")
    public DataResult deleteBatch(@RequestBody List<String> jcajbhList) {
        int result = jaglYljamxService.deleteData(jcajbhList);
        return DataResult.success(result);
    }

    @PostMapping("/yljamx/getYljamxSwjgjcks")
    @ResponseBody
    public DataResult getYljamxSwjgjcks() {
        LambdaQueryWrapper<JaglYljamxEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(JaglYljamxEntity::getSsdw);
        queryWrapper.groupBy(JaglYljamxEntity::getSsdw);
        queryWrapper.orderByDesc(JaglYljamxEntity::getSsdw);
        List<JaglYljamxEntity> list = jaglYljamxService.list(queryWrapper);
        return DataResult.success(list);
    }

    @PostMapping("/qtjamx/getQtjamxSwjgjcks")
    @ResponseBody
    public DataResult getQtjamxSwjgjcks() {
        LambdaQueryWrapper<QtjamxEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(QtjamxEntity::getSsdw);
        queryWrapper.groupBy(QtjamxEntity::getSsdw);
        queryWrapper.orderByDesc(QtjamxEntity::getSsdw);
        List<QtjamxEntity> list = qtjamxService.list(queryWrapper);
        return DataResult.success(list);
    }

    @PostMapping("/cljamx/getCljamxSwjgjcks")
    @ResponseBody
    public DataResult getCljamxSwjgjcks() {
        LambdaQueryWrapper<CljamxEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(CljamxEntity::getSsdw);
        queryWrapper.groupBy(CljamxEntity::getSsdw);
        queryWrapper.orderByDesc(CljamxEntity::getSsdw);
        List<CljamxEntity> list = cljamxService.list(queryWrapper);
        return DataResult.success(list);
    }

    @PostMapping("/yljamx/editYljamx")
    @ResponseBody
    @LogAnnotation(title = "一类积案", action = "编辑一类积案明细")
    public DataResult editYljamx(@RequestBody JaglYljamxEntity jaglYljamxEntity) {
        boolean result = jaglYljamxService.updateById(jaglYljamxEntity);
        return DataResult.success(result);
    }

    @PostMapping("/qtjamx/queryQtjamxTable")
    @ApiOperation(value = "查询其他积案明细")
    @LogAnnotation(title = "积案管理", action = "查询其他积案明细")
    public DataResult queryQtjamxTable(@RequestBody QtjamxEntity QtjamxEntity) throws ParseException {
        return DataResult.success(qtjamxService.queryQtjamxTable(QtjamxEntity));
    }

    @PostMapping("/qtjamx/editQtjamx")
    @ResponseBody
    @LogAnnotation(title = "其他积案", action = "编辑其他积案明细")
    public DataResult editQtjamx(@RequestBody QtjamxEntity QtjamxEntity) {
        boolean result = qtjamxService.updateById(QtjamxEntity);
        return DataResult.success(result);
    }

    @PostMapping("/cljamx/editCljamx")
    @ResponseBody
    @LogAnnotation(title = "超六积案", action = "编辑超六积案明细")
    public DataResult editCljamx(@RequestBody CljamxEntity cljamxEntity) {
        boolean result = cljamxService.updateById(cljamxEntity);
        return DataResult.success(result);
    }

    @PostMapping("/cljamx/queryCljamxTable")
    @ApiOperation(value = "查询超六积案明细")
    @LogAnnotation(title = "积案管理", action = "查询超六积案明细")
    public DataResult queryCljamxTable(@RequestBody CljamxEntity CljamxEntity) throws ParseException {
        return DataResult.success(cljamxService.queryCljamxTable(CljamxEntity));
    }

    private boolean isRowEmpty(Row row) {
        if (row == null) return true;
        for (int c = 0; c <= row.getLastCellNum(); c++) {
            Cell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                if (cell.getCellType() == CellType.STRING && !cell.getStringCellValue().trim().isEmpty()) return false;
                if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.BOOLEAN) return false;
            }
        }
        return true;
    }

    // 工具方法：读取字符串单元格
    private String getStringCellValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                // 判断是否为整数
                double numValue = cell.getNumericCellValue();
                if (numValue == (long) numValue) {
                    return String.valueOf((long) numValue);  // 整数返回无小数点
                } else {
                    return String.valueOf(numValue);  // 小数返回原样
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                try {
                    return cell.getStringCellValue();
                } catch (IllegalStateException e) {
                    // 公式计算结果为数字时
                    double formulaNumValue = cell.getNumericCellValue();
                    if (formulaNumValue == (long) formulaNumValue) {
                        return String.valueOf((long) formulaNumValue);
                    } else {
                        return String.valueOf(formulaNumValue);
                    }
                }
            case BLANK:
            case ERROR:
            default:
                return "";
        }
    }

    // 工具方法：读取数字单元格
    private Double getDoubleCellValue(Cell cell) {
        if (cell == null) return null;
        try {
            if (cell.getCellType() == CellType.NUMERIC) {
                return cell.getNumericCellValue();
            } else if (cell.getCellType() == CellType.STRING) {
                String val = cell.getStringCellValue().trim();
                if (!val.isEmpty()) {
                    return Double.parseDouble(val);
                }
            }
        } catch (Exception e) {
            log.debug("getDoubleCellValue error:{}", e.getMessage());
        }
        return null;
    }

    // 工具方法：读取日期单元格
    private Date getDateCellValue(Cell cell) {
        if (cell == null) return null;
        try {
            if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
                return cell.getDateCellValue();
            } else if (cell.getCellType() == CellType.STRING) {
                String dateStr = cell.getStringCellValue().trim();
                if (dateStr.isEmpty()) return null;

                // 支持多种常见格式
                List<String> patterns = Arrays.asList("yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd");
                for (String pattern : patterns) {
                    try {
                        return new SimpleDateFormat(pattern).parse(dateStr);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (Exception ex) {
            log.debug("getDateCellValue error:{}", ex.getMessage());
        }
        return null;
    }

}